package com.briup.corejava.chap12;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Test063_TcpServer {
    public static void main(String[] args) {
        // 构建服务器对象
        ServerSocket serverSocket = null;
        Socket socket = null;
        int port = 8888;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("服务器已经启动，正在监听"+port+"端口...");
            socket = serverSocket.accept();
            System.out.println(socket);
            // 从socket里读取数据出来
            // 要用输入流
            InputStream in = socket.getInputStream();
            int len = -1;
            byte[] buf = new byte[1024];
            System.out.println("服务器读到的数据为：");
            while ((len = in.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }
            System.out.println("服务器接收数据完毕，准备返回响应...");
//            in.close();
            socket.shutdownInput();

            OutputStream out = socket.getOutputStream();
            out.write("收到帐号密码，允许登陆".getBytes());
            out.flush();
            out.close();
            System.out.println("服务器响应成功，服务结束！");

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
